import routeNames from "../../utils/routeNames";
import {useNavigate} from "react-router-dom";
import {ChangeEvent, useEffect, useState} from "react";
import UserWithBalance from "../../models/UserWithBalance";
import {getLeaderboard} from "../../http/userApi";
import GetUsersByFilterDto from "../../utils/dto/user/getUsersByFilterDto";
import {getPaginationRange} from "../../functions/getPaginationRange";

const LeaderboardPage = () => {
    const navigate = useNavigate();
    const [users, setUsers] = useState<UserWithBalance[]>([]);
    const [pageNumber, setPageNumber] = useState(1);
    const [pageSize] = useState(15);
    const [filter, setFilter] = useState(localStorage.getItem('LeaderboardPageSearchValue') ?? "");
    const [searchTrigger, setSearchTrigger] = useState(false);
    const [totalPages, setTotalPages] = useState(1);

    useEffect(() => {
        setSearchTrigger(false);
        fetchLeaderboard();
    }, [pageNumber, searchTrigger]);

    const fetchLeaderboard = () => {
        let dto = new GetUsersByFilterDto(pageNumber, pageSize, filter)
        getLeaderboard(dto)
            .then(response => {
                if (response.status === 200) {
                    setUsers(response.data.users);
                    let newTotalPages = response.data.count / pageSize
                    setTotalPages(newTotalPages == 0 ? 1 : newTotalPages);
                } else {
                    console.error(response.statusText);
                }
            })
    };

    const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
        setFilter(e.target.value);
        localStorage.setItem('LeaderboardPageSearchValue', e.target.value);
    };

    const handleSearchClick = () => {
        setUsers([])
        setSearchTrigger(true);
        setPageNumber(1);
    };

    const handlePageChange = (newPageNumber: number) => {
        setPageNumber(newPageNumber);
    };

    return (
        <>
            <div className="gamfi-breadcrumbs-section">
                <div className="container">
                    <div className="row">
                        <div className="col-lg-5">
                            <div className="breadcrumbs-area sec-heading">
                                <div className="sub-inner mb-15">
                                    <a className="breadcrumbs-link" style={{cursor: 'pointer'}}
                                       onClick={() => navigate(routeNames.HOME_PAGE)}>Home</a>
                                    <span className="sub-title">Leaderboard</span>
                                    <img className="heading-left-image" src="/assets/images/icons/steps.png"
                                         alt="Steps-Image"/>
                                </div>
                                <h2 className="title mb-0">Leaderboard</h2>
                            </div>
                        </div>
                        <div className="col-lg-7 breadcrumbs-form mr-0 md-pt-30">
                            <form onSubmit={(e) => {
                                e.preventDefault();
                                fetchLeaderboard();
                            }}>
                                <input type="text" id="Search" name="search" value={filter}
                                       onChange={(e) => handleSearchChange(e)}
                                       placeholder="Search by name"/>
                                <span className="submit" onClick={handleSearchClick}><i
                                    className="icon-search"></i><input type="submit"/></span>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <div className="leaderboard-table-list pb-140 md-pb-80 pt-55">
                <div className="container">
                    <table>
                        <thead>
                        <tr>
                            <th># RANK</th>
                            <th>Name</th>
                            <th>Balance</th>
                        </tr>
                        </thead>
                        <tbody>
                        {users && users.sort((a, b) => b.balance - a.balance).map((user, index) => (
                            <tr key={user.userId}>
                                <td>{(pageNumber - 1) * pageSize + index + 1}</td>
                                <td>{user.username}</td>
                                <td>${user.balance.toFixed(2)}</td>
                            </tr>
                        ))}
                        </tbody>
                    </table>
                    <div className="gamfi-navigation text-center mt-40">
                        <ul>
                            <li>
                                <a
                                    onClick={() => pageNumber > 1 && handlePageChange(pageNumber - 1)}
                                    className={pageNumber === 1 ? "disabled" : ""}
                                    style={{cursor: pageNumber === 1 ? "default" : "pointer"}}
                                >
                                    <i className="icon-Vector"></i>
                                </a>
                            </li>
                            {getPaginationRange(pageNumber, pageSize, totalPages).map((page, index) => (
                                <li key={index}>
                                    <a
                                        style={{cursor: page === '...' ? 'default' : 'pointer'}}
                                        className={pageNumber === page ? "active" : ""}
                                        onClick={() => typeof page === 'number' && handlePageChange(page)}
                                    >
                                        {page}
                                    </a>
                                </li>
                            ))}
                            <li>
                                <li>
                                    <a onClick={() => pageNumber < totalPages && handlePageChange(pageNumber + 1)}
                                       className={pageNumber != totalPages ? "disabled" : ""}
                                       style={{cursor: pageNumber != totalPages ? "pointer" : "default"}}>
                                        <i className="icon-arrow_right"></i>
                                    </a>
                                </li>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </>
    )
}

export default LeaderboardPage